package com.wngbms.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class LockDemo {

    public static void main(String[] args) throws InterruptedException {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6379")
                .setDatabase(0);

        RedissonClient redissonClient = Redisson.create(config);

        CountDownLatch countDownLatch = new CountDownLatch(2);

        Runnable runnable = () -> {
            while (true) {
                RLock rLock = redissonClient.getLock("DIS_LOCK");
                try {
//                boolean tryLock = rLock.tryLock(500, 15000, TimeUnit.MILLISECONDS);
//                boolean tryLock = rLock.tryLock(500, 150000, TimeUnit.MILLISECONDS);
                    boolean tryLock = true;
                    rLock.lock(15000, TimeUnit.MILLISECONDS);
                    if (tryLock) {
                        log.info("get lock");
                        Thread.sleep(6000);
                    }
                } catch (InterruptedException e) {
                    log.error("get lock exp", e);
                } finally {
                    log.info("release lock");
                    try {
                        rLock.unlock();
                    } catch (Exception e) {
                        log.error("release lock exp", e);
                    }
                    countDownLatch.countDown();
                }
            }
        };

//        new Thread(runnable, "t1").start();
        new Thread(runnable, "t2").start();

//        countDownLatch.await();
        log.info("end...................");
    }

}
